package com.kdtech.analyse.tool;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.utils.DateUtils;

public class ParseTool {

	private List<ParseLogic> parseLogic=new ArrayList<ParseLogic>();

	private Document doc=null;
	public ParseTool(Document doc){
		this.doc=doc;
	}
	/**
	 * 添加解析逻辑
	 * @param logic
	 */
	public void addParseLogic(ParseLogic logic){
		this.parseLogic.add(logic);
	}

	/**
	 * 根据之前添加的解析逻辑解析，返回String
	 * @return
	 */
	public String parse(){
		String retStr=null;
		if(doc!=null && parseLogic!=null){
			for (ParseLogic logic : parseLogic) {
				Elements select = doc.select(logic.getSelect());
				switch(logic.getType()){
					case html:
						retStr = select.html();
					case text:
						retStr = select.text();
					case attr:
						if(logic.getAttrName()!=null)
						retStr = select.attr(logic.getAttrName());
				}
				if(StringUtils.isNotBlank(retStr)){
					SubstrLogic subLogic = logic.getSubLogic();
					if(subLogic!=null){
						SubstrType type = subLogic.getType();
						switch(type){
						case before:
							retStr= StringUtils.substringBefore(retStr, subLogic.getSubStr());
							break;
						case after:
							retStr= StringUtils.substringAfter(retStr, subLogic.getSubStr());
							break;
						case between:
							retStr= StringUtils.substringBetween(retStr, subLogic.getStartStr(),subLogic.getEndStr());
							break;
						case beforeLast:
							retStr= StringUtils.substringBeforeLast(retStr, subLogic.getSubStr());
							break;
						}
					}
					if(StringUtils.isNotBlank(retStr))
						break;
				}
			}
		}
		parseLogic.clear();
		return retStr;
	}

	/**
	 * 根据之前添加的解析逻辑解析时间，返回Long
	 * @return
	 */
	public Long parseDate(){
		Long date=null;
		if(doc!=null && parseLogic!=null){
			for (ParseLogic logic : parseLogic) {
				Elements select = doc.select(logic.getSelect());
				switch(logic.getType()){
					case html:
						date = DateUtils.matchDate(select.html());
					case text:
						date = DateUtils.matchDate(select.text());
					case attr:
						if(logic.getAttrName()!=null)
							date = DateUtils.matchDate(select.attr(logic.getAttrName()));
				}
				if(date!=null){
					break;
				}
			}
		}
		parseLogic.clear();
		return date;
	}

}
